/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.elvis.music;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.elvis.music.R;
import com.elvis.music.adapter.AlbumViewAdapter;
import com.elvis.music.adapter.ArtistListCursorAdapter;
import com.elvis.music.adapter.GenresListAdapter;
import com.elvis.music.adapter.HistoryAdapter;
import com.elvis.music.adapter.MusicListAdapter;
import com.elvis.music.adapter.MyPlayListAdapter;
import com.elvis.music.adapter.MyPlayListItemAdapter;
import com.elvis.music.adapter.TypeMusicListAdapter;
import com.elvis.music.adapter.TypeViewAdapter;
import com.elvis.music.database.SQLHelper;
import com.elvis.music.model.Forder;
import com.elvis.music.model.Music;
import com.elvis.music.model.MusicPositionInfo;
import com.elvis.music.picture.Rotate3dAnimation;
import com.elvis.music.service.IPlayService;
import com.elvis.music.service.MusicService;
import com.elvis.music.util.MusicOperate;
import com.elvis.music.util.SharedPreference;
import com.elvis.music.util.Util;
import com.elvis.music.view.ViewDragableSpace;
import com.elvis.music.view.ViewLrc;

/**
 * home activity
 * 
 * @author LeiKang
 */
public class HomeActivity extends Activity implements OnClickListener, PropertyChangeListener,
        OnItemClickListener, OnChildClickListener {
    /**
     * service绑定
     */
    private ServiceConnection serviceConnection;

    /**
     * 状态设置
     */
    private SharedPreference mSharedPreference;

    /**
     * 实例musicoperate
     */
    private MusicOperate mMusicOperate;

    /**
     * 歌曲list
     */
    private List<Music> mListMusic;

    /**
     * 滑动ViewGroup
     */
    private ViewDragableSpace mViewDragableSpace;

    /**
     * 显示歌曲列表
     */
    private ListView mListView;

    /**
     * 歌词秀
     */
    private ViewLrc mViewLrc;

    /**
     * Layout填充
     */
    private LayoutInflater mLayoutInflater;

    /**
     * 滑动group填充view
     */
    private View mLayoutView;

    /**
     * typeview flipper
     */
    private ViewFlipper typeViewFlipper;

    /**
     * 当前选中MusicId
     */
    private int mCurrentMusicId;

    /**
     * 当前选中music
     */
    private Music mCurrentMusic;

    /**
     * service传回的播放信息
     */
    private MusicPositionInfo mMusicPositionInfo;

    /**
     * service name
     */
    private ComponentName component;

    /**
     * 绑定service
     */
    private IPlayService countService;

    /**
     * 播放控制btn：上一首
     */
    private ImageButton mBtnPrev;

    /**
     * 播放or暂停
     */
    private ImageButton mBtnPlay;

    /**
     * 播放暂停图标
     */
    private ImageView imgPlay;

    /**
     * 下一首
     */
    private ImageButton mBtnNext;

    /**
     * 弹出menu
     */
    private ImageButton mIndMenu;

    /**
     * top 滑屏控制btn： 主页面
     */
    private ImageButton mIndMain;

    /**
     * 歌曲列表页面
     */
    private ImageButton mIndList;

    /**
     * 歌词秀
     */
    private ImageButton mIndLyric;

    /**
     * 声音控制btn
     */
    private ImageButton mImgBtnVolume;

    private ImageView mImgVoice;

    /**
     * title文本显示
     */
    private TextView mTextViewTitle;

    /**
     * 播放模式：循环，随机，单曲重复
     */
    private ImageButton mIndPlayMode;

    /**
     * listviewlayout之外的 图标显示
     */
    private ImageView mImgPlayMode;

    /**
     * listviewlayout 图标显示
     */
    private ImageView mImgBtListBack;

    /**
     * 记录当前 屏幕
     */
    private int mCurrentScreen;

    /**
     * 进度条
     */
    private SeekBar skbGuage;

    /**
     * 进度条右侧 显示当前歌曲总时长 txt
     */
    private TextView txtDuration;

    /**
     * 进度条左侧 需要每秒刷新的字符串值
     */
    private String playingTimeString;

    /**
     * 进度条左侧 显示当前播放进度时间 txt
     */
    private TextView txtPlayingTime;

    /**
     * menu菜单Dialog ，这里重写menu响应，弹出dialog
     */
    private Dialog menuDialog;

    /**
     * menu 起始为上下两个gridview top
     */
    private GridView menuGridTop;

    /**
     * menu gridview 填充view
     */
    private View menuView;

    /**
     * 传入或调用的当前context
     */
    private Context mContext;

    /**
     * 每秒 控制刷新 进度条 左侧 text
     */
    private TimerHandler timerHandler;

    /**
     * Timer设置，sleep 为1000ms
     */
    private Timer mTimer;

    /**
     * 与timerHandler ，timer 配合使用
     */
    private MyTimerTask mMyTimerTask;

    /**
     * 用于picture 切换
     */
    private ViewGroup mContainer;

    /**
     * single bg 背景图片
     */
    private ImageView singleBg;

    private MusicChangeBroadCastReceiver mMusicChangeBroadCastReceiver;

    private MusicPositionBroadCastReceiver mMusicPositionBroadCastReceiver;

    private SlidingDrawer mDrawer;

    private GridView mTypeView;

    private ImageView lyricsHandleImg;

    private AlbumViewAdapter mAlbumViewAdapter;

    private ExpandableListView mExpandableListView;

    private ArtistListCursorAdapter mExpandableListCursorAdapter;

    private ListView mAlbumListView;

    private ListView mGenresListView;

    // private ListView mForderListView;

    private ListView mMyPlayListView;

    private ListView mItemListView;

    private ListView mMyItemListView;

    private ListView historyListView;

    private HistoryAdapter historyAdapter;

    // private ForderListAdapter mForderListAdapter;

    private GenresListAdapter mGenresListAdapter;

    private MyPlayListAdapter mMyPlayListAdapter;

    private TypeMusicListAdapter mTypeMusicListAdapter;

    private int typeViewPosition = 0;

    private Cursor mChacheCursor;

    private Music itemLongClickPosition;

    private String[] playListId;

    private MyPlayListItemAdapter mMyPlayListItemAdapter;

    private int lastVoice;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /** 设置全屏 */
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.homeactivity);
        mContext = this;

        if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            Toast.makeText(this, R.string.sdcard_is_not_exit, Toast.LENGTH_SHORT).show();
        }

        mMusicOperate = new MusicOperate();
        mListMusic = mMusicOperate.getAllMusic(this);
        viewInit();

        if (mListMusic.size() != 0) {
            setInit();
        } else {
            TextView noMusic = (TextView) findViewById(R.id.no_music);
            noMusic.setVisibility(View.VISIBLE);
        }

    }

    private void viewInit() {
        /** sharepreference 实例 */
        mSharedPreference = new SharedPreference(this);
        /** 当前播放信息 从service时时获取 */
        mMusicPositionInfo = new MusicPositionInfo();
        /** layout 滑动类，主要实现各个layout切换，可进行监听 */
        mViewDragableSpace = (ViewDragableSpace) findViewById(R.id.viewdragablespace);
        mViewDragableSpace.addPropertyChangeListener(this);
        /** Layout适配 */
        mLayoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        /** 背景图片 linearlayout */
        mContainer = (ViewGroup) findViewById(R.id.container);
        /** 背景图片 imageview */
        singleBg = (ImageView) findViewById(R.id.singlebg);
        /* listlayout 相关 */
        mLayoutView = findViewById(R.id.listview);
        mListView = (ListView) mLayoutView.findViewById(R.id.playList);
        /** 显示所有歌曲的listview */
        mListView.setAdapter(new MusicListAdapter(this.mLayoutInflater.getContext(), mListMusic));
        /* typelayout 相关 */
        mLayoutView = findViewById(R.id.typeview);
        typeViewFlipper = (ViewFlipper) mLayoutView.findViewById(R.id.typeViewFlipper);

        mTypeView = (GridView) mLayoutView.findViewById(R.id.typelistgrid);

        mAlbumListView = (ListView) mLayoutView.findViewById(R.id.albumlist);
        historyListView = (ListView) mLayoutView.findViewById(R.id.historylist);
        mGenresListView = (ListView) mLayoutView.findViewById(R.id.schoollist);
        // mForderListView = (ListView)
        // mLayoutView.findViewById(R.id.forderlist);
        mMyPlayListView = (ListView) mLayoutView.findViewById(R.id.playlist);
        mItemListView = (ListView) mLayoutView.findViewById(R.id.itemlist);
        mMyItemListView = (ListView) mLayoutView.findViewById(R.id.myitemlist);
        mExpandableListView = (ExpandableListView) mLayoutView.findViewById(R.id.artistlist);

        /** 显示歌词 view */
        /* playlayout 相关 */
        mLayoutView = findViewById(R.id.playview);
        /** 播放界面 mini歌词 */
        mViewLrc = (ViewLrc) mLayoutView.findViewById(R.id.play_lyrics);
        /** 进度条 */
        skbGuage = (SeekBar) findViewById(R.id.skbGuage);

        /** 进度text计时 */
        txtDuration = (TextView) findViewById(R.id.txtDuration);
        txtPlayingTime = (TextView) findViewById(R.id.txtLapse);

        lyricsHandleImg = (ImageView) mLayoutView.findViewById(R.id.lyricsHandleImg);

        /* 播放控制 位于屏幕下方，点击响应button 进行歌曲播放/暂停 上一曲/下一曲 设置 以及播放模式切换 */
        mBtnPrev = (ImageButton) findViewById(R.id.btnPrev);
        mBtnPlay = (ImageButton) findViewById(R.id.btnPlay);
        mBtnNext = (ImageButton) findViewById(R.id.btnNext);

        /** 播放界面 播放/暂停 图片切换 */
        imgPlay = (ImageView) findViewById(R.id.imgPlay);
        /** 显示menu dialog ，同点击menu键 */
        mIndMenu = (ImageButton) findViewById(R.id.IndMenu);

        /* 播放模式设置 */
        mIndPlayMode = (ImageButton) findViewById(R.id.IndPlayMode);
        mImgPlayMode = (ImageView) findViewById(R.id.imgPlayMode);
        mImgBtListBack = (ImageView) findViewById(R.id.ImgBtListBack);

        /* 滑屏显示 ImageButton 位于 屏幕上方，点击相应button分别显示不同界面 */
        mIndMain = (ImageButton) findViewById(R.id.IndMain);
        mIndList = (ImageButton) findViewById(R.id.IndList);
        mIndLyric = (ImageButton) findViewById(R.id.IndLyric);

        mImgBtnVolume = (ImageButton) findViewById(R.id.ImgBtnVolume);
        mImgVoice = (ImageView) findViewById(R.id.ImgVolume);
        /* 播放layout title */
        mTextViewTitle = (TextView) findViewById(R.id.txtTitle);

        /* 设置typelayout 图标 */
        mTypeView.setAdapter(new TypeViewAdapter(this));
        /** 菜单初始化 */
        initMenu();
        /* 界面初始化 layout设置为playlayout，默认歌曲为 第一首 */
        mViewDragableSpace.setScreenId(mSharedPreference.getInt(Util.PANEL_ID, Util.PLAY_PANEL_ID));
        mCurrentScreen = mSharedPreference.getInt(Util.LAST_SCREEN_ID, 0);
        mCurrentMusicId = mSharedPreference.getInt(Util.LAST_PLAY_MUSIC, 0);
        screenSelect(mCurrentScreen);
        typeViewFlipper.setDisplayedChild(0);
    }

    private void setInit() {
        MusicApplication.getInstance().setListMusic(mListMusic);

        serviceConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName name, IBinder service) {
                countService = (IPlayService) service;
                if (countService != null)
                    countService.closeDeskTopLrc();
            }

            public void onServiceDisconnected(ComponentName name) {
                countService = null;
            }
        };
        /*----*/
        mViewLrc.setlrcPosition(0);

        mListView.setOnItemClickListener(this);
        mListView.setSelection(mCurrentMusicId);

        mListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                itemLongClickPosition = mListMusic.get(position);
                new AlertDialog.Builder(mContext).setTitle(
                        mContext.getString(R.string.music_options)).setIcon(
                        android.R.drawable.ic_dialog_info).setItems(
                        mContext.getResources().getStringArray(R.array.item_long_click),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        countService.itemClickPlay(itemLongClickPosition.id);
                                        imgPlay.setImageResource(R.drawable.img_playback_bt_play);
                                        dialog.dismiss();
                                        break;
                                    case 1:
                                        dialog.dismiss();
                                        Cursor cursor = mContext.getContentResolver().query(
                                                SQLHelper.CONTENT_URI_PLAY_LIST, null, null, null,
                                                null);
                                        if (cursor != null) {
                                            String[] arr = new String[cursor.getCount()];
                                            playListId = new String[cursor.getCount()];
                                            cursor.moveToFirst();
                                            for (int i = 0; i < cursor.getCount(); i++) {
                                                arr[i] = cursor.getString(1);
                                                playListId[i] = cursor.getString(0);
                                                cursor.moveToNext();
                                            }
                                            new AlertDialog.Builder(mContext).setItems(arr,
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog,
                                                                int which) {
                                                            ContentValues values = new ContentValues();
                                                            values.put("_play_list_id",
                                                                    playListId[which]);
                                                            values.put("_music_path",
                                                                    itemLongClickPosition.path);
                                                            values.put("_duration",
                                                                    itemLongClickPosition.duration);
                                                            values.put("_description",
                                                                    itemLongClickPosition.album);
                                                            Cursor cursor = mContext
                                                                    .getContentResolver()
                                                                    .query(
                                                                            SQLHelper.CONTENT_URI_PLAY_LIST_MUSIC_MAP,
                                                                            null,
                                                                            "_play_list_id = ? and _music_path = ?",
                                                                            new String[] {
                                                                                    playListId[which],
                                                                                    itemLongClickPosition.path
                                                                            }, null);
                                                            if (cursor != null
                                                                    && cursor.getCount() > 0)
                                                                Toast.makeText(mContext,
                                                                        R.string.music_is_exit,
                                                                        Toast.LENGTH_SHORT).show();
                                                            else {
                                                                mContext
                                                                        .getContentResolver()
                                                                        .insert(
                                                                                SQLHelper.CONTENT_URI_PLAY_LIST_MUSIC_MAP,
                                                                                values);
                                                                Toast.makeText(mContext,
                                                                        R.string.success_add,
                                                                        Toast.LENGTH_SHORT).show();
                                                            }
                                                            dialog.dismiss();
                                                        }
                                                    }).show();
                                        }
                                        break;
                                    case 2:
                                        dialog.dismiss();
                                        String musicDetail = mContext
                                                .getString(R.string.music_name)
                                                + "： "
                                                + itemLongClickPosition.title
                                                + "\n\n"
                                                + mContext.getString(R.string.artist)
                                                + "： "
                                                + itemLongClickPosition.artist
                                                + "\n\n"
                                                + mContext.getString(R.string.album)
                                                + "： "
                                                + itemLongClickPosition.album
                                                + "\n\n"
                                                + mContext.getString(R.string.format)
                                                + itemLongClickPosition.mimeType
                                                + "\n\n"
                                                + mContext.getString(R.string.duration)
                                                + "： "
                                                + itemLongClickPosition.duration
                                                + "\n\n"
                                                + mContext.getString(R.string.path)
                                                + ": "
                                                + itemLongClickPosition.path.substring("/mnt/"
                                                        .length());
                                        new AlertDialog.Builder(mContext).setTitle(
                                                R.string.music_info).setIcon(
                                                android.R.drawable.ic_dialog_map).setMessage(
                                                musicDetail).setNegativeButton(R.string.ok, null)
                                                .show();
                                        break;
                                    default:
                                        dialog.dismiss();
                                        break;
                                }
                            }
                        }).show();

                return false;
            }
        });

        mExpandableListCursorAdapter = new ArtistListCursorAdapter(mContext, mMusicOperate
                .getArtistCursor(mContext, null, null), R.layout.track_list_item_group,
                new String[] {}, new int[] {}, R.layout.track_list_item_child, new String[] {},
                new int[] {});
        mExpandableListView.setAdapter(mExpandableListCursorAdapter);
        mExpandableListView.setOnChildClickListener(this);

        mAlbumViewAdapter = new AlbumViewAdapter(mContext, R.layout.album_list_item, mMusicOperate
                .getAlbumCursor(mContext, null, null), new String[] {}, new int[] {});
        mAlbumListView.setAdapter(mAlbumViewAdapter);

        mItemListView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (mChacheCursor != null && mChacheCursor.getCount() != 0) {
                    mChacheCursor.moveToPosition(position);
                    for (int i = 0; i < mListMusic.size(); i++) {
                        if (mListMusic.get(i).id == mChacheCursor.getInt(0))
                            countService.itemClickPlay(i);
                    }
                    imgPlay.setImageResource(R.drawable.img_playback_bt_play);
                }
            }
        });

        mAlbumListView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = mMusicOperate.getAlbumCursor(mContext, null, null);
                cursor.moveToPosition(position);
                String currentAlbumId = cursor.getString(0);
                cursor = mContext.getContentResolver().query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MusicOperate.mCursorCols,
                        MediaStore.Audio.AudioColumns.ALBUM_ID + "=? and " + Util.TIME_WHERE,
                        new String[] {
                            currentAlbumId
                        }, null);

                mTypeMusicListAdapter = new TypeMusicListAdapter(mContext, cursor);
                mChacheCursor = cursor;
                mItemListView.setAdapter(mTypeMusicListAdapter);
                typeViewFlipper.setDisplayedChild(6);
                typeViewPosition = 2;
            }
        });
        historyListView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // if (mChacheCursor != null && mChacheCursor.getCount() != 0) {
                // mChacheCursor.moveToPosition(position);
                // countService.itemClickPlay(mChacheCursor.getInt(1) - 1);
                // }
            }
        });

        mMyPlayListAdapter = new MyPlayListAdapter(mContext);
        mMyPlayListView.setAdapter(mMyPlayListAdapter);
        mMyPlayListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = mContext.getContentResolver().query(
                        SQLHelper.CONTENT_URI_PLAY_LIST, null, null, null, null);
                cursor.moveToPosition(position);

                Cursor cur = mContext.getContentResolver().query(
                        SQLHelper.CONTENT_URI_PLAY_LIST_MUSIC_MAP, null, "_play_list_id= ?",
                        new String[] {
                            Integer.toString(cursor.getInt(0))
                        }, null);
                mMyPlayListItemAdapter = new MyPlayListItemAdapter(mContext, cur);
                mMyItemListView.setAdapter(mMyPlayListItemAdapter);
                typeViewFlipper.setDisplayedChild(7);
                typeViewPosition = 4;
            }
        });

        mGenresListAdapter = new GenresListAdapter(mContext);
        mGenresListView.setAdapter(mGenresListAdapter);

        mGenresListView.setOnItemClickListener(new OnItemClickListener() {
            // bug
            String[] cols = new String[] {
                    "audio._id AS _id", MediaStore.Audio.Media.ARTIST,
                    MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.TITLE,
                    MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.MIME_TYPE,
                    MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.ARTIST_ID,
                    MediaStore.Audio.Media.DURATION, MediaStore.Audio.Genres._ID + " as genre_id"
            };

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Cursor cursor = MusicOperate.getAudioGenres(mContext);
                cursor.moveToPosition(position);
                String currentGenresId = cursor.getString(0);

                cursor = mContext.getContentResolver().query(
                        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols,
                        MediaStore.Audio.Genres.Members.GENRE_ID + "=?   ", new String[] {
                            currentGenresId
                        }, null);

                mTypeMusicListAdapter = new TypeMusicListAdapter(mContext, cursor);
                mChacheCursor = cursor;
                mItemListView.setAdapter(mTypeMusicListAdapter);
                typeViewFlipper.setDisplayedChild(6);
                typeViewPosition = 3;

            }
        });

        mTypeView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    typeViewFlipper.setDisplayedChild(1);
                } else if (position == 1) {

                    typeViewFlipper.setDisplayedChild(2);
                } else if (position == 2) {

                    typeViewFlipper.setDisplayedChild(3);
                } else if (position == 3) {
                    mMyPlayListAdapter = new MyPlayListAdapter(mContext);
                    mMyPlayListView.setAdapter(mMyPlayListAdapter);
                    typeViewFlipper.setDisplayedChild(4);
                } else if (position == 4) {
                    Cursor cursor = mContext.getContentResolver().query(
                            SQLHelper.CONTENT_URI_HISTORY, null, null, null, null);
                    historyAdapter = new HistoryAdapter(mContext, cursor);
                    // mChacheCursor = cursor;
                    historyListView.setAdapter(historyAdapter);
                    typeViewFlipper.setDisplayedChild(5);
                    // cursor.close();
                }
                typeViewPosition = 0;
                mImgBtListBack.setImageResource(R.drawable.img_top_bt_back_s);
            }
        });

        mTypeView.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 4) {
                    new AlertDialog.Builder(mContext).setTitle(R.string.delete_the_play_history)
                            .setIcon(android.R.drawable.ic_menu_close_clear_cancel)
                            .setNegativeButton(getString(R.string.cancel), null).setPositiveButton(
                                    R.string.ok, new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            mContext.getContentResolver().delete(
                                                    SQLHelper.CONTENT_URI_HISTORY, null, null);
                                            Toast.makeText(mContext,
                                                    R.string.play_history_is_delete,
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    }).show();
                } else if (position == 3) {
                    new AlertDialog.Builder(mContext).setTitle(R.string.list_options).setIcon(
                            android.R.drawable.ic_dialog_info).setItems(
                            mContext.getResources().getStringArray(R.array.my_play_img_click),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            dialog.dismiss();
                                            LayoutInflater factory = LayoutInflater.from(mContext);
                                            final View textEntryView = factory.inflate(
                                                    R.layout.alert_dialog_text_entry, null);
                                            new AlertDialog.Builder(mContext).setIcon(
                                                    android.R.drawable.ic_input_add).setTitle(
                                                    R.string.new_list).setView(textEntryView)
                                                    .setPositiveButton(R.string.ok,
                                                            new DialogInterface.OnClickListener() {
                                                                public void onClick(
                                                                        DialogInterface dialog,
                                                                        int whichButton) {
                                                                    TextView tv = (TextView) textEntryView
                                                                            .findViewById(R.id.username_edit);

                                                                    if (tv.getText() != null
                                                                            && tv.getText() != "") {
                                                                        ContentValues values = new ContentValues();
                                                                        values.put("_title", tv
                                                                                .getText()
                                                                                .toString());
                                                                        mContext
                                                                                .getContentResolver()
                                                                                .insert(
                                                                                        SQLHelper.CONTENT_URI_PLAY_LIST,
                                                                                        values);
                                                                        Toast
                                                                                .makeText(
                                                                                        mContext,
                                                                                        R.string.success_add,
                                                                                        Toast.LENGTH_SHORT)
                                                                                .show();
                                                                    } else
                                                                        Toast
                                                                                .makeText(
                                                                                        mContext,
                                                                                        R.string.list_name_can_not_be_null,
                                                                                        Toast.LENGTH_SHORT)
                                                                                .show();
                                                                }
                                                            }).setNegativeButton(R.string.cancel,
                                                            null).show();
                                            break;
                                        case 1:
                                            new AlertDialog.Builder(mContext).setTitle(
                                                    R.string.delete_the_play_list).setIcon(
                                                    android.R.drawable.ic_menu_close_clear_cancel)
                                                    .setNegativeButton(R.string.cancel, null)
                                                    .setPositiveButton(R.string.ok,
                                                            new DialogInterface.OnClickListener() {
                                                                public void onClick(
                                                                        DialogInterface dialog,
                                                                        int whichButton) {
                                                                    mContext
                                                                            .getContentResolver()
                                                                            .delete(
                                                                                    SQLHelper.CONTENT_URI_PLAY_LIST,
                                                                                    "_title!=?",
                                                                                    new String[] {
                                                                                        getString(R.string.my_favorites)
                                                                                    });
                                                                    mContext
                                                                            .getContentResolver()
                                                                            .delete(
                                                                                    SQLHelper.CONTENT_URI_PLAY_LIST_MUSIC_MAP,
                                                                                    null, null);
                                                                    Toast
                                                                            .makeText(
                                                                                    mContext,
                                                                                    R.string.play_list_is_delete,
                                                                                    Toast.LENGTH_SHORT)
                                                                            .show();
                                                                }
                                                            }).show();

                                        default:
                                            break;
                                    }
                                }
                            }).show();
                }

                return false;
            }
        });

        skbGuage.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    /** 点击 进度条 反向设置 service中播放 */
                    countService.setPosition(progress);
                }
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mTimer = new Timer(true);
        /** 1000ms */

        timerHandler = new TimerHandler(this);
        mMyTimerTask = new MyTimerTask(this);
        mTimer.schedule(mMyTimerTask, 0, 1000);

        mDrawer = (SlidingDrawer) mLayoutView.findViewById(R.id.drawer);
        mDrawer.startLayoutAnimation();
        mDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
            public void onDrawerOpened() {
                lyricsHandleImg.setImageResource(R.drawable.lyrics_handle_expand);
                MusicApplication.getInstance().setLrcCenter(mDrawer.getWidth() / 2);
            }
        });
        mDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {

            public void onDrawerClosed() {
                lyricsHandleImg.setImageResource(R.drawable.lyrics_handle_shrink);
                MusicApplication.getInstance().setLrcCenter(40);
            }
        });
        mDrawer.setOnDrawerScrollListener(new SlidingDrawer.OnDrawerScrollListener() {
            public void onScrollEnded() {
            }

            public void onScrollStarted() {
            }
        });
        mBtnPrev.setOnClickListener(this);
        mBtnPlay.setOnClickListener(this);
        mBtnNext.setOnClickListener(this);

        mIndMenu.setOnClickListener(this);

        mIndPlayMode.setOnClickListener(this);
        mIndMain.setOnClickListener(this);
        mIndList.setOnClickListener(this);
        mIndLyric.setOnClickListener(this);

        mImgBtnVolume.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                AudioManager audioManager2 = (AudioManager) mContext
                        .getSystemService(Context.AUDIO_SERVICE);
                // int max =
                // audioManager2.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                int current = audioManager2.getStreamVolume(AudioManager.STREAM_MUSIC);
                if (current != 0) {
                    lastVoice = current;
                    mImgVoice.setImageResource(R.drawable.img_volume_mute);
                    audioManager2.setStreamVolume(AudioManager.STREAM_MUSIC, 0,
                            AudioManager.FX_FOCUS_NAVIGATION_UP & ~AudioManager.FLAG_SHOW_UI);

                } else {
                    mImgVoice.setImageResource(R.drawable.img_volume_btn);
                    audioManager2.setStreamVolume(AudioManager.STREAM_MUSIC, lastVoice,
                            AudioManager.FX_FOCUS_NAVIGATION_UP & ~AudioManager.FLAG_SHOW_UI);
                }

            }
        });

        /** ====================== onresume移至oncreate ======================== */
        if (mListMusic.size() != 0)
            mCurrentMusic = mListMusic.get(mCurrentMusicId);
        /** 设置歌词 ，picture */
        if (mCurrentMusic != null) {
            applyRotation(null, 0, 180);
        }
        /* 变量用于链接activity和service */
        component = new ComponentName(this, MusicService.class);
        this.bindService(new Intent(Util.MUSIC_SERVICE_TAG), this.serviceConnection,
                BIND_AUTO_CREATE);
        /** 开启service */
        Intent mIntent = new Intent(Util.START_ACTION);
        mIntent.setComponent(component);
        startService(mIntent);
        /* 界面播放模式显示 */
        showPlayModel();
        if (MusicApplication.getInstance().getIsPlaying())
            imgPlay.setImageResource(R.drawable.img_playback_bt_play);
        else
            imgPlay.setImageResource(R.drawable.img_playback_bt_pause);
        screenSelect(mCurrentScreen);

        /* 读取当前音乐所有文件夹 */
        List<Forder> sdPath;
        sdPath = new ArrayList<Forder>();
        String oldPath = "";
        Forder forder = new Forder();
        for (int i = 0; i < mListMusic.size(); i++) {
            String newPath = mListMusic.get(i).path;
            newPath = newPath.substring(0, newPath.lastIndexOf("/"));
            if (!newPath.equals(oldPath)) {
                forder.path = newPath;
                forder.isChecked = true;
                sdPath.add(forder);
                oldPath = newPath;
            }
        }
        MusicApplication.getInstance().setSdPath(sdPath);
    }

    /**
     * 界面选择时 ImageButton 高亮显示 默认情况为0 播放界面
     * 
     * @author leikang
     * @param screenId
     */
    private void screenSelect(int screenId) {
        mCurrentScreen = screenId;
        if (screenId == 0) {
            /** 点击或滑动选择至 界面 当前界面对应ImageButton 高亮 */
            mIndMain.setEnabled(false);
            mIndList.setEnabled(true);
            mIndLyric.setEnabled(true);
            /** playlayout和lrclayout界面 显示播放模式图标，listlayout显示返回图标 */
            mImgPlayMode.setVisibility(ImageView.VISIBLE);
            mImgBtListBack.setVisibility(ImageView.INVISIBLE);
        } else if (screenId == 1) {
            mIndMain.setEnabled(true);
            mIndList.setEnabled(false);
            mIndLyric.setEnabled(true);
            mImgPlayMode.setVisibility(ImageView.VISIBLE);
            mImgBtListBack.setVisibility(ImageView.INVISIBLE);
        } else if (screenId == 2) {
            mIndMain.setEnabled(true);
            mIndList.setEnabled(true);
            mIndLyric.setEnabled(false);
            mImgPlayMode.setVisibility(ImageView.INVISIBLE);
            mImgBtListBack.setVisibility(ImageView.VISIBLE);
        }
    }

    /**
     * 刷新 lrcview ，minilrc，播放进度
     * 
     * @author leikang
     */
    private void flashView() {
        /** 从service中获取musicplayinginfo */
        mMusicPositionInfo = countService.getMusicPlayingInfo();
        mCurrentMusic = mListMusic.get(mMusicPositionInfo.id);
        /* ================= 刷新前台界面 ===================== */
        /** 当前页面为 lrcview */
        if ((mCurrentScreen == 0)) {
            mViewLrc.setlrcPosition(mMusicPositionInfo.position);
        }
        /** 确保 CurrentMusic与mMusicPositionInfo 均不为空 */
        if ((mCurrentScreen == 0)) {
            skbGuage.setMax(mCurrentMusic.totalTime);
            skbGuage.setProgress(mMusicPositionInfo.position);
        }
        /* ================================================== */
    }

    /**
     * 响应点击事件
     * 
     * @author leikang
     */
    public void onClick(View v) {
        if (v == mBtnPrev) {
            /** 向service发送播放前一首指令 */
            countService.preSong();
        } else if (v == mBtnPlay) {
            /** 当前正在播放，则暂停，反之则播放，并时时修改 状态图标 */
            imgPlay.setImageResource(R.drawable.img_playback_bt_play);
            countService.playingOrPause();
            if (MusicApplication.getInstance().getIsPlaying())
                imgPlay.setImageResource(R.drawable.img_playback_bt_play);
            else
                imgPlay.setImageResource(R.drawable.img_playback_bt_pause);
        } else if (v == mBtnNext) {
            imgPlay.setImageResource(R.drawable.img_playback_bt_play);
            /** 向service发送播放下一首指令 */
            countService.nextSong();
        } else if (v == mIndMenu) {
            /** 显示menu */
            resetMenuItem();
            menuDialog.show();
        } else if (v == mIndMain) {
            /* 点击 屏幕上方layout imageButton 切换响应 layout */
            mViewDragableSpace.setScreenId(Util.PLAY_PANEL_ID);
            /** 高亮 button */
            screenSelect(0);
        } else if (v == mIndList) {
            mViewDragableSpace.setScreenId(Util.LIST_PANEL_ID);
            screenSelect(1);
        } else if (v == mIndLyric) {
            mViewDragableSpace.setScreenId(Util.LRC_PANEL_ID);
            screenSelect(2);
        } else if (v == mIndPlayMode) {
            if (mCurrentScreen == 2) {
                /** ============= 控制播放列表 =============== */
                // if (typeViewFlipper.getDisplayedChild() == 4) {
                // List<Forder> sdForder = mForderListAdapter.getForder();
                // MusicApplication.getInstance().setSdPath(sdForder);
                // }
                if (mChacheCursor != null)
                    mChacheCursor.close();
                // if (typeViewPosition != 0) {
                if (typeViewFlipper.getDisplayedChild() != 0) {
                    typeViewFlipper.setDisplayedChild(typeViewPosition);
                    if (typeViewPosition == 0)
                        mImgBtListBack.setImageResource(R.drawable.img_top_bt_back);
                    typeViewPosition = 0;
                } else
                    mImgBtListBack.setImageResource(R.drawable.img_top_bt_back);
                // }
            } else {
                /** ============= 设置播放模式 =============== */
                String model = mSharedPreference
                        .getString(Util.TAG_PLAY_MODEL, Util.PLAY_MODEL_ALL);
                if (model.equals(Util.PLAY_MODEL_ALL)) {
                    mSharedPreference.saveString(Util.TAG_PLAY_MODEL, Util.PLAY_MODEL_RANDOM);
                    mSharedPreference.showMessage(getString(R.string.random));
                    mImgPlayMode.setImageResource(R.drawable.icon_playmode_shuffle);
                } else if (model.equals(Util.PLAY_MODEL_RANDOM)) {
                    mSharedPreference.saveString(Util.TAG_PLAY_MODEL, Util.PLAY_MODEL_SINGLE);
                    mSharedPreference.showMessage(getString(R.string.single));
                    mImgPlayMode.setImageResource(R.drawable.icon_playmode_repeat_single);
                } else if (model.equals(Util.PLAY_MODEL_SINGLE)) {
                    mSharedPreference.saveString(Util.TAG_PLAY_MODEL, Util.PLAY_MODEL_ALL);
                    mSharedPreference.showMessage(getString(R.string.all));
                    mImgPlayMode.setImageResource(R.drawable.icon_playmode_repeat);
                }
            }
        }

    }

    /**
     * Activity 结束，解除service相关绑定，保存状态
     * 
     * @author leikang
     */
    protected void onDestroy() {
        if (mCurrentScreen == 0) {
            mSharedPreference.saveInt(Util.PANEL_ID, Util.PLAY_PANEL_ID);
            mSharedPreference.saveInt(Util.LAST_SCREEN_ID, mCurrentScreen);
        } else if (mCurrentScreen == 1) {
            mSharedPreference.saveInt(Util.PANEL_ID, Util.LIST_PANEL_ID);
            mSharedPreference.saveInt(Util.LAST_SCREEN_ID, mCurrentScreen);
        } else if (mCurrentScreen == 2) {
            mSharedPreference.saveInt(Util.PANEL_ID, Util.LRC_PANEL_ID);
            mSharedPreference.saveInt(Util.LAST_SCREEN_ID, mCurrentScreen);
        }
        /* ===================== 保存相关状态 ============================== */
        /* 解除绑定 */
        if (mListMusic.size() != 0)
            this.unbindService(serviceConnection);
        super.onDestroy();
    }

    /**
     * 监听滑动view
     * 
     * @author leikang
     */
    public void propertyChange(PropertyChangeEvent event) {
        if (event.getNewValue().equals(Util.PLAY_PANEL_ID)) {
            mCurrentScreen = 0;
            screenSelect(0);
        } else if (event.getNewValue().equals(Util.LIST_PANEL_ID)) {
            mCurrentScreen = 1;
            screenSelect(1);
        } else if (event.getNewValue().equals(Util.LRC_PANEL_ID)) {
            mCurrentScreen = 2;
            screenSelect(2);
        }
    }

    /**
     * listmusic 点击 时间响应
     * 
     * @author leikang
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        countService.itemClickPlay(position);
        imgPlay.setImageResource(R.drawable.img_playback_bt_play);
    }

    /**
     * 根据设置的播放状态显示 imageplayview
     * 
     * @author leikang
     */
    private void showPlayModel() {
        String model = mSharedPreference.getString(Util.TAG_PLAY_MODEL, Util.PLAY_MODEL_ALL);
        if (model.equals(Util.PLAY_MODEL_ALL)) {
            mImgPlayMode.setImageResource(R.drawable.icon_playmode_repeat);
        } else if (model.equals(Util.PLAY_MODEL_RANDOM)) {
            mImgPlayMode.setImageResource(R.drawable.icon_playmode_shuffle);
        } else if (model.equals(Util.PLAY_MODEL_SINGLE)) {
            mImgPlayMode.setImageResource(R.drawable.icon_playmode_repeat_single);
        }
    }

    /* ======================== 初始化menu ========================== */
    /**
     * 初始化menu
     * 
     * @author leikang
     */
    private void initMenu() {
        menuView = View.inflate(this, R.layout.menu, null);
        menuDialog = new Dialog(HomeActivity.this, R.style.dialog);
        menuDialog.setContentView(menuView);
        menuDialog.setCanceledOnTouchOutside(true);
        menuDialog.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_MENU)
                    dialog.dismiss();
                return false;
            }
        });
        menuGridTop = (GridView) menuView.findViewById(R.id.menuGridChange);
        resetMenuItem();
    }

    /**
     * 显示menu item前，先确定当前哪一layout
     */
    private void resetMenuItem() {
        if (mCurrentScreen != -1) {
            menuGridTop.setAdapter(getMenuAdapter(getResources().getStringArray(
                    R.array.menu_name_array_top_play), Util.menu_image_array_top_play));
            /** 监听menu选项 **/
            menuGridTop.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    switch (arg2) {
                        case Util.MENU_TOP_DESK_LYRIC:// 桌面歌词
                            menuDialog.dismiss();
                            boolean isDeskTopShow = mSharedPreference
                                    .getBoolean(Util.IS_DESK_TOP_LRC_SHOW);
                            mSharedPreference
                                    .saveBoolean(Util.IS_DESK_TOP_LRC_SHOW, !isDeskTopShow);
                            if (!isDeskTopShow)
                                mSharedPreference
                                        .showMessage(getString(R.string.hidden_the_desk_lrc));
                            else
                                mSharedPreference
                                        .showMessage(getString(R.string.display_the_desk_lrc));
                            break;
                        case Util.MENU_MUSIC_INFO:// 歌曲信息

                            if (mCurrentMusic != null) {
                                String musicDetail = mContext.getString(R.string.music_name) + "： "
                                        + mCurrentMusic.title + "\n\n"
                                        + mContext.getString(R.string.artist) + "： "
                                        + mCurrentMusic.artist + "\n\n"
                                        + mContext.getString(R.string.album) + "： "
                                        + mCurrentMusic.album + "\n\n"
                                        + mContext.getString(R.string.format) + "： MP3" + "\n\n"
                                        + mContext.getString(R.string.duration) + "： "
                                        + mCurrentMusic.duration + "\n\n"
                                        + mContext.getString(R.string.path) + ": "
                                        + mCurrentMusic.path.substring("/mnt/".length());

                                new AlertDialog.Builder(mContext).setTitle(R.string.music_info)
                                        .setIcon(android.R.drawable.ic_dialog_dialer).setMessage(
                                                musicDetail).setNegativeButton(R.string.ok, null)
                                        .show();
                            }
                            menuDialog.dismiss();
                            break;
                        case Util.MENU_PLAY_MODEL:// 播放模式
                            menuDialog.dismiss();
                            new AlertDialog.Builder(mContext).setTitle(R.string.play_model)
                                    .setIcon(android.R.drawable.ic_dialog_info).setItems(
                                            getResources().getStringArray(R.array.play_model_tag),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog,
                                                        int which) {
                                                    switch (which) {
                                                        case 0:
                                                            mSharedPreference.saveString(
                                                                    Util.TAG_PLAY_MODEL,
                                                                    Util.PLAY_MODEL_ALL);
                                                            break;
                                                        case 1:
                                                            mSharedPreference.saveString(
                                                                    Util.TAG_PLAY_MODEL,
                                                                    Util.PLAY_MODEL_SINGLE);
                                                            break;
                                                        case 2:
                                                            mSharedPreference.saveString(
                                                                    Util.TAG_PLAY_MODEL,
                                                                    Util.PLAY_MODEL_RANDOM);
                                                            break;
                                                    }
                                                    showPlayModel();
                                                    dialog.dismiss();
                                                }
                                            }).show();
                            break;
                        case Util.MENU_LYRIC_EFFIC:// 显示效果
                            boolean isLrcKtv = mSharedPreference.getBoolean(Util.IS_LRC_KTV);
                            mSharedPreference.saveBoolean(Util.IS_LRC_KTV, !isLrcKtv);
                            if (isLrcKtv)
                                mSharedPreference.showMessage(getString(R.string.lyrics_gradient));
                            else
                                mSharedPreference
                                        .showMessage(getString(R.string.cancle_lyrics_gradient));
                            menuDialog.dismiss();
                            break;
                        case Util.MENU_HELP:// 帮助
                            menuDialog.dismiss();
                            new AlertDialog.Builder(mContext).setTitle(R.string.help).setIcon(
                                    android.R.drawable.ic_dialog_map).setMessage(
                                    R.string.help_message).setNegativeButton(R.string.ok, null)
                                    .show();
                            break;
                        case Util.MENU_ABOUT:// 关于
                            menuDialog.dismiss();
                            new AlertDialog.Builder(mContext).setTitle(R.string.about).setIcon(
                                    android.R.drawable.ic_dialog_info).setMessage(
                                    R.string.about_message).setNegativeButton(R.string.ok, null)
                                    .show();
                            break;
                        case Util.MENU_BACK:// 退出
                            MusicApplication.getInstance().setIsPlaying(false);
                            menuDialog.cancel();
                            countService.stopMedia();
                            Intent i = new Intent();
                            i.setClass(HomeActivity.this, MusicService.class);
                            mContext.stopService(i);
                            finish();
                            break;
                    }

                }
            });
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");
        return super.onCreateOptionsMenu(menu);
    }

    private SimpleAdapter getMenuAdapter(String[] menuNameArray, int[] imageResourceArray) {
        ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < menuNameArray.length; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("itemImage", imageResourceArray[i]);
            map.put("itemText", menuNameArray[i]);
            data.add(map);
        }
        SimpleAdapter simperAdapter = new SimpleAdapter(this, data, R.layout.menu_btn_item,
                new String[] {
                        "itemImage", "itemText"
                }, new int[] {
                        R.id.menuBtnItemImage, R.id.menuBtnItemContent
                });
        return simperAdapter;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menuDialog == null) {
            menuDialog = new AlertDialog.Builder(this).setView(menuView).show();
        } else {
            resetMenuItem();
            menuDialog.setContentView(menuView);
            menuDialog.show();
        }
        return false;// 返回为true 则显示系统menu
    }

    /* =========================== 刷新 播放时间 相关================================= */
    /**
     * TimerTask
     * 
     * @author leikang
     */
    class MyTimerTask extends TimerTask {

        public MyTimerTask(HomeActivity p) {

        }

        public void run() {
            timerHandler.sendEmptyMessage(0);
        }
    }

    class TimerHandler extends Handler {
        public TimerHandler(HomeActivity m) {

        }

        @Override
        public void handleMessage(Message msg) {
            if (!mViewDragableSpace.isHuaDong) {
                toTime();
                if (mCurrentMusic == null)
                    return;
                /* 刷新 播放时间 */
                txtDuration.setText(mCurrentMusic.duration);
                txtPlayingTime.setText(playingTimeString);
                /* 动态显示TextTitle */
                mTextViewTitle.setText(mCurrentMusic.title);
            }
        }
    }

    /**
     * ms 转换为 00:00格式
     * 
     * @author leikang
     */
    private void toTime() {
        int time = mMusicPositionInfo.position;
        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        minute %= 60;
        playingTimeString = String.format("%02d:%02d", minute, second);
    }

    /* ====================== 切换图片 相关=============================== */
    /**
     * 切换图片并旋转
     * 
     * @author leikang
     */
    private void applyRotation(Bitmap mBitmap, float start, float end) {
        final float centerX = mContainer.getWidth() / 2.0f;
        final float centerY = mContainer.getHeight() / 2.0f;
        final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, centerX, centerY,
                310.0f, true);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(mBitmap));
        mContainer.startAnimation(rotation);
    }

    private final class DisplayNextView implements Animation.AnimationListener {
        private final Bitmap mBitmap;

        private DisplayNextView(Bitmap bm) {
            mBitmap = bm;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            mContainer.post(new SwapViews(mBitmap));
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    private final class SwapViews implements Runnable {
        private Bitmap mBitmap;

        public SwapViews(Bitmap bm) {
            mBitmap = bm;
        }

        public void run() {

            final float centerX = mContainer.getWidth() / 2.0f;
            final float centerY = mContainer.getHeight() / 2.0f;
            Rotate3dAnimation rotation;

            singleBg.setVisibility(View.GONE);
            singleBg.setImageBitmap(mBitmap);
            singleBg.setVisibility(View.VISIBLE);
            singleBg.requestFocus();

            rotation = new Rotate3dAnimation(180, 0, centerX, centerY, 310.0f, false);

            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());

            mContainer.startAnimation(rotation);
        }
    }

    /* ======================= 接受广播相关 ====================== */

    private class MusicChangeBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            applyRotation(null, 0, 90);
            mViewLrc.init();
            /* 显示当前播放 */
            mListView.setSelection(mMusicPositionInfo.id);
        }
    }

    private class MusicPositionBroadCastReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            flashView();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (countService != null)
            countService.closeDeskTopLrc();
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public void onStart() {
        IntentFilter musicChangeBroadCastFilter = new IntentFilter(Util.MUSIC_CHANGE_BROADCAST);
        mMusicChangeBroadCastReceiver = new MusicChangeBroadCastReceiver();
        registerReceiver(mMusicChangeBroadCastReceiver, musicChangeBroadCastFilter);

        IntentFilter musicPositionBroadCastFilter = new IntentFilter(Util.MUSIC_POSITION_BROADCAST);
        mMusicPositionBroadCastReceiver = new MusicPositionBroadCastReceiver();
        registerReceiver(mMusicPositionBroadCastReceiver, musicPositionBroadCastFilter);
        super.onStart();
    }

    @Override
    public void onStop() {
        if (countService != null)
            countService.showDeskTopLrc();
        unregisterReceiver(mMusicChangeBroadCastReceiver);
        unregisterReceiver(mMusicPositionBroadCastReceiver);
        super.onStop();
    }

    /* ====================== 艺术家adapter ============================== */

    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
            int childPosition, long id) {
        Cursor mArtistCursor = mMusicOperate.getArtistCursor(mContext, null, null);
        String mCurrentArtistId;
        Cursor cursor;
        String mCurrentAlbumId = Long.valueOf(id).toString();

        mArtistCursor.moveToPosition(groupPosition);
        mCurrentArtistId = mArtistCursor.getString(mArtistCursor
                .getColumnIndex(MediaStore.Audio.Artists._ID));
        cursor = mContext.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MusicOperate.mCursorCols,
                MediaStore.Audio.AudioColumns.ALBUM_ID + "=? and "
                        + MediaStore.Audio.AudioColumns.ARTIST_ID + "=?", new String[] {
                        mCurrentAlbumId, mCurrentArtistId
                }, null);
        mTypeMusicListAdapter = new TypeMusicListAdapter(mContext, cursor);
        mChacheCursor = cursor;
        mItemListView.setAdapter(mTypeMusicListAdapter);
        typeViewFlipper.setDisplayedChild(6);
        typeViewPosition = 1;
        imgPlay.setImageResource(R.drawable.img_playback_bt_play);
        return true;
    }

}
